#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <sys/msg.h>
#include <pthread.h>
#include "pub_define.h"
#include "shmem.h"
#include "msg_queue_peer.h"
#include "list.h"
#include "cJSON.h"

// 设备类型定义
#define DEV_TYPE_MODBUS 1
#define DEV_TYPE_STM32 0

<<<<<<< HEAD
// 统一数据类型定义（与Modbus进程完全一致）
#define DATA_TYPE_BOOL  0  // 布尔类型
#define DATA_TYPE_INT   1  // 整数类型
#define DATA_TYPE_FLOAT 2  // 浮点类型

// 最大设备数（与Modbus进程匹配）
#define MAX_NODE 128

// 共享内存结构定义（与Modbus进程完全一致）
typedef union val_t {
    int b_val;     // bool类型存储空间
    int i_val;     // 整形值存储空间
    float f_val;   // 浮点值存储空间
=======
// 修改后的数据类型定义（匹配JSON配置）
#define DATA_TYPE_BOOL 1  // type=1
#define DATA_TYPE_INT 2   // type=2
#define DATA_TYPE_FLOAT 3 // type=3

// 共享内存结构定义
typedef union
{
    int b_val;   // bool类型存储空间
    int i_val;   // 整形值存储空间
    float f_val; // 浮点值存储空间
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
} val_t;

typedef struct std_node
{
    int key;
<<<<<<< HEAD
    int type;            // 数据类型 (0=bool, 1=int, 2=float)
    int dev_type;        // 设备类型 (0=STM32, 1=Modbus)
=======
    int type;     // 数据类型 (1=bool, 2=int, 3=float)
    int dev_type; // 设备类型 (0=STM32, 1=Modbus)
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
    val_t old_val;
    val_t new_val;
    int ret;
} std_node_t;

<<<<<<< HEAD
// 控制消息结构（与Modbus进程完全一致）
typedef struct ctl_node {
    long mtype;   // 消息类型
    int value;    // 控制值
    int key;      // 设备键值
=======
// 控制消息结构
typedef struct ctl_node
{
    long type;
    int key;
    int value;
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
} control_node_t;

// STM32设备配置
typedef struct
{
    int key;
    char name[32];
<<<<<<< HEAD
    int type;            // 统一数据类型
    int index;           // 设备在STM32区域中的索引
=======
    int type;      // 数据类型 (1=bool, 2=int, 3=float)
    int json_type; // JSON中的原始类型 (1=bool, 2=int, 3=float)
    int index;     // 设备在STM32区域中的索引 (0-3)
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
} stm32_device_t;

// 全局变量
stm32_device_t *stm32_devices = NULL;
int stm32_device_count = 0;
pthread_mutex_t shm_mutex = PTHREAD_MUTEX_INITIALIZER;
<<<<<<< HEAD
static int g_acceptfd = -1;
=======

// 共享内存布局
#define SHM_TOTAL_DEVICES 8
#define STM32_DEVICE_COUNT 4
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1

// 共享内存指针
static int *shm_total_devices = NULL;
static std_node_t *shm_arr = NULL;

<<<<<<< HEAD
// 类型映射函数（与Modbus进程一致）
int map_json_type(int json_type) {
    switch (json_type) {
    case 1: return DATA_TYPE_BOOL;
    case 2: return DATA_TYPE_INT;
    case 3: return DATA_TYPE_FLOAT;
    default: return DATA_TYPE_INT;
    }
}

// 共享内存设备初始化
void init_shm_device(std_node_t *device, int key, int type, int dev_type) {
    device->key = key;
    device->type = type;
    device->dev_type = dev_type;
    device->old_val.i_val = 0;
    device->new_val.i_val = 0;
    device->ret = -1;
}

// 在共享内存中查找设备
std_node_t *find_shm_device_by_key(int key) {
    if (!shm_arr || !shm_total_devices) return NULL;
    
    for (int i = 0; i < *shm_total_devices; i++) {
        if (shm_arr[i].key == key) {
            return &shm_arr[i];
        }
    }
    return NULL;
}

// JSON配置文件解析
int parse_config(const char *config_path) {
=======
// 修改后的类型映射函数
int map_json_type(int json_type)
{
    // 直接使用相同类型值，无需转换
    return json_type;
}

// 修改后的共享内存设备初始化
void init_shm_device(std_node_t *device, int key, int type, int dev_type)
{
    device->key = key;
    device->type = type; // 使用新的类型值
    device->dev_type = dev_type;
    device->old_val.b_val = 0;
    device->new_val.b_val = 0;
    device->ret = -1; // 初始化为错误状态
}

// 修改后的JSON配置文件解析
int parse_config(const char *config_path)
{
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
    FILE *fp = fopen(config_path, "r");
    if (!fp)
    {
        perror("fopen error");
        return -1;
    }

    char buf[4096] = {0};
    size_t read_size = fread(buf, 1, 4095, fp);
    fclose(fp);

    if (read_size == 0)
    {
        perror("fread error");
        return -1;
    }

    cJSON *root = cJSON_Parse(buf);
    if (!root)
    {
        printf("JSON解析错误: %s\n", cJSON_GetErrorPtr());
        return -1;
    }

    // 解析STM32设备
    cJSON *stm32_obj = cJSON_GetObjectItem(root, "stm32");
    if (!stm32_obj)
    {
        printf("未找到stm32节点\n");
        cJSON_Delete(root);
        return -1;
    }

    cJSON *data_array = cJSON_GetObjectItem(stm32_obj, "data");
    if (!data_array)
    {
        printf("未找到data数组\n");
        cJSON_Delete(root);
        return -1;
    }

    stm32_device_count = cJSON_GetArraySize(data_array);
    if (stm32_device_count <= 0)
    {
        printf("未找到STM32设备配置\n");
        cJSON_Delete(root);
        return -1;
    }
<<<<<<< HEAD
    
    if (stm32_device_count > MAX_NODE) {
        printf("警告: STM32设备数超过配置限制 (%d > %d)\n", 
               stm32_device_count, MAX_NODE);
        stm32_device_count = MAX_NODE;
    }
    
    stm32_devices = malloc(stm32_device_count * sizeof(stm32_device_t));
    if (!stm32_devices) {
=======

    if (stm32_device_count > STM32_DEVICE_COUNT)
    {
        printf("警告: STM32设备数超过配置限制 (%d > %d)\n",
               stm32_device_count, STM32_DEVICE_COUNT);
    }

    stm32_devices = malloc(STM32_DEVICE_COUNT * sizeof(stm32_device_t));
    if (!stm32_devices)
    {
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
        perror("内存分配失败");
        cJSON_Delete(root);
        return -1;
    }
<<<<<<< HEAD
    
    memset(stm32_devices, 0, stm32_device_count * sizeof(stm32_device_t));
    
    for (int i = 0; i < stm32_device_count; i++) {
=======

    // 清空设备结构
    memset(stm32_devices, 0, STM32_DEVICE_COUNT * sizeof(stm32_device_t));

    for (int i = 0; i < stm32_device_count; i++)
    {
        if (i >= stm32_device_count)
            break;

>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
        cJSON *item = cJSON_GetArrayItem(data_array, i);
        if (!item)
            continue;

        cJSON *key_obj = cJSON_GetObjectItem(item, "key");
        cJSON *name_obj = cJSON_GetObjectItem(item, "name");
        cJSON *type_obj = cJSON_GetObjectItem(item, "type");

        if (!key_obj || !name_obj || !type_obj)
        {
            printf("设备配置缺少必要字段，跳过\n");
            continue;
        }

        stm32_devices[i].key = key_obj->valueint;
        stm32_devices[i].type = map_json_type(type_obj->valueint);
        stm32_devices[i].index = i;

        if (name_obj->valuestring)
        {
            strncpy(stm32_devices[i].name, name_obj->valuestring,
                    sizeof(stm32_devices[i].name) - 1);
<<<<<<< HEAD
        } else {
            snprintf(stm32_devices[i].name, sizeof(stm32_devices[i].name), 
                     "STM32设备_%d", i);
        }
        
        printf("配置STM32设备: %s, key=%d, 类型=%d\n", 
               stm32_devices[i].name, stm32_devices[i].key, 
               stm32_devices[i].type);
=======
            stm32_devices[i].name[sizeof(stm32_devices[i].name) - 1] = '\0';
        }
        else
        {
            snprintf(stm32_devices[i].name, sizeof(stm32_devices[i].name),
                     "STM32设备_%d", i);
        }

        printf("配置STM32设备: %s, key=%d, JSON类型=%d, 内部类型=%d\n",
               stm32_devices[i].name, stm32_devices[i].key,
               stm32_devices[i].json_type, stm32_devices[i].type);
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
    }

    cJSON_Delete(root);
    return 0;
}

<<<<<<< HEAD
// 共享内存初始化
int init_shared_memory() {
    struct shm_param para;
    size_t shm_size = sizeof(int) + MAX_NODE * sizeof(std_node_t);
    
    // 初始化共享内存
    if (shm_init(&para, "shm_test", shm_size) != 0) {
        printf("共享内存初始化失败\n");
        return -1;
=======
// 修改后的共享内存初始化
int init_shared_memory()
{
    struct shm_param para;
    size_t shm_size = sizeof(int) + SHM_TOTAL_DEVICES * sizeof(std_node_t);

    // 尝试初始化共享内存
    if (shm_init(&para, "shm", shm_size) != 0)
    {
        printf("共享内存初始化失败，尝试重新连接\n");

        // 尝试直接连接现有共享内存
        key_t key = ftok("/tmp/ipc/shmem/shm", 'j'); // 使用与驱动相同的MAGIC_ID
        if (key == -1)
        {
            perror("ftok失败");
            return -1;
        }

        int shmid = shmget(key, shm_size, 0666);
        if (shmid == -1)
        {
            perror("shmget失败");
            return -1;
        }

        para.id = shmid;
        para.size = shm_size;
        strcpy(para.name, "shm");
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
    }

    // 获取共享内存地址
    shm_total_devices = (int *)shm_getaddr(&para);
    if (shm_total_devices == NULL)
    {
        printf("获取共享内存地址失败\n");
        return -1;
    }

    // 设置共享内存布局
    shm_arr = (std_node_t *)(shm_total_devices + 1);
<<<<<<< HEAD
    
    // 初始化设备总数
    if (*shm_total_devices == 0) {
        *shm_total_devices = MAX_NODE;
        printf("设置设备总数: %d\n", MAX_NODE);
=======

    // 如果设备总数为0，则设置为8
    if (*shm_total_devices == 0)
    {
        *shm_total_devices = SHM_TOTAL_DEVICES;
        printf("设置设备总数: %d\n", SHM_TOTAL_DEVICES);
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
    }

    // 初始化STM32设备区域
<<<<<<< HEAD
    for (int i = 0; i < stm32_device_count; i++) {
        std_node_t *device = find_shm_device_by_key(stm32_devices[i].key);
        if (!device) {
            // 如果未找到，使用下一个可用位置
            if (i < MAX_NODE) {
                device = &shm_arr[i];
            } else {
                printf("错误: 超出共享内存设备限制\n");
                break;
            }
        }
        
        init_shm_device(device, 
                      stm32_devices[i].key, 
                      stm32_devices[i].type,
                      DEV_TYPE_STM32);
        printf("初始化共享内存STM32设备[%d]: key=%d, type=%d\n", 
=======
    for (int i = 0; i < stm32_device_count && i < STM32_DEVICE_COUNT; i++)
    {
        init_shm_device(&shm_arr[i],
                        stm32_devices[i].key,
                        stm32_devices[i].type,
                        DEV_TYPE_STM32);
        printf("初始化共享内存STM32设备[%d]: key=%d, type=%d\n",
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
               i, stm32_devices[i].key, stm32_devices[i].type);
    }

    return 0;
}

<<<<<<< HEAD
// 控制消息处理线程
void *handler_thread(void *arg)
{
    control_node_t control;
    int msgid = msgget(ftok("topic", 0), 0666 | IPC_CREAT); // 获取消息队列ID
    
    if (msgid == -1) {
        perror("STM32进程获取消息队列失败");
        return NULL;
    }
    
    while (1) {
        // 从消息队列接收控制信息
        int ret = msg_queue_recv("topic", &control, sizeof(control_node_t), 0, IPC_NOWAIT);
        
        if (ret > 0) {
            // 判断key是否属于STM32设备范围
            if (control.key < STM32_KEY_MIN || control.key > STM32_KEY_MAX) {
                // 不属于STM32设备，放回队列
                if (msgsnd(msgid, &control, sizeof(control_node_t) - sizeof(long), IPC_NOWAIT) == -1) {
                    perror("STM32进程放回消息失败");
                }
                printf("STM32进程将消息放回队列: key=%d\n", control.key);
                continue;
            }

            // 处理STM32设备的控制消息
            printf("STM32进程处理控制: key=%d, value=%d\n", control.key, control.value);

            // 构造控制JSON
            cJSON *root = cJSON_CreateObject();
            cJSON *data_obj = cJSON_CreateObject();
            
            if (root && data_obj) {
                // 查找设备名
                const char *dev_name = "未知设备";
                for (int i = 0; i < stm32_device_count; i++) {
                    if (stm32_devices[i].key == control.key) {
                        dev_name = stm32_devices[i].name;
                        break;
                    }
                }
                
                // 添加控制值
                cJSON_AddNumberToObject(data_obj, dev_name, control.value);
                cJSON_AddItemToObject(root, "control", data_obj);
                
                // 生成JSON字符串
                char *json_str = cJSON_PrintUnformatted(root);
                if (json_str) {
                    printf("发送控制指令: %s\n", json_str);
                    
                    // 发送给STM32设备
                    if (g_acceptfd > 0) {
                        send(g_acceptfd, json_str, strlen(json_str), 0);
                    } else {
                        printf("警告: 无活跃的STM32连接\n");
                    }
                    
                    free(json_str);
                }
                cJSON_Delete(root);
            }
=======
void *handler_thread(void *arg)
{
    control_node_t control;

    int fd = *(int *)arg;

    while (1)
    {

       //printf("等待控制信息...\n");

        // 从消息队列接收控制信息
        if (msg_queue_recv("control", &control, sizeof(control_node_t), 0, 0) < 0)
        {
            // 打印具体错误码和原因
            printf("msg_queue_recv error: %s (errno=%d)\n", strerror(errno), errno);
            sleep(1);
            continue;
        }
        printf("收到控制信息: key=%d, value=%d\n", control.key, control.value);
        // 判断 key 是否落在 STM32 设备范围：300 < key < 400
        if (control.key > 300 && control.key < 400)
        {
            // 构造 JSONcd
            cJSON *root = cJSON_CreateObject();
            if (!root)
            {
                fprintf(stderr, "cJSON_CreateObject failed\n");
                continue;
            }
            cJSON_AddNumberToObject(root, "key", control.key);
            cJSON_AddNumberToObject(root, "value", control.value);

            char *json_str = cJSON_PrintUnformatted(root);
            if (json_str)
            {
                ssize_t send_len = send(fd, json_str, strlen(json_str), 0);

                

                if (send_len == -1)
                {
                    perror("send failed");
                    printf("send error: fd=%d, json=%s\n", fd, json_str);
                }
                else if (send_len != strlen(json_str))
                {
                    printf("send incomplete: sent %zd/%zu bytes\n", send_len, strlen(json_str));
                }
                else
                {
                    printf("send complete: sent %zd bytes\n", send_len);
                }

                free(json_str);
            }
            else
            {
                fprintf(stderr, "cJSON_PrintUnformatted failed\n");
            }
            cJSON_Delete(root);
        }
        else
        {
            // 不是 STM32 设备，原有处理（例如 Modbus）
            printf("Non-STM32 device, key=%d, value=%d\n",
                   control.key, control.value);
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
        }
        usleep(10000); // 降低CPU占用（原100ms可调整为10ms）
    }
    return NULL;
}

<<<<<<< HEAD
// 更新共享内存
void update_shared_memory(int key, const char *value) {
    pthread_mutex_lock(&shm_mutex);
    
    std_node_t *device = find_shm_device_by_key(key);
    if (!device) {
        printf("警告: key=%d的设备在共享内存中未找到\n", key);
        pthread_mutex_unlock(&shm_mutex);
        return;
    }
    
    // 保存旧值
    device->old_val = device->new_val;
    
    // 根据数据类型更新新值
    switch (device->type) {
        case DATA_TYPE_BOOL:
            device->new_val.b_val = (strcmp(value, "1") == 0) ? 1 : 0;
            break;
        case DATA_TYPE_INT:
            device->new_val.i_val = atoi(value);
            break;
        case DATA_TYPE_FLOAT:
            device->new_val.f_val = atof(value);
=======
// 修改后的共享内存更新函数
void update_shared_memory(int key, const char *value)
{
    if (shm_arr == NULL)
    {
        printf("共享内存未初始化\n");
        return;
    }

    pthread_mutex_lock(&shm_mutex);

    // 在整个设备数组中查找匹配的key
    for (int i = 0; i < *shm_total_devices; i++)
    {
        if (shm_arr[i].key == key && shm_arr[i].dev_type == DEV_TYPE_STM32)
        {
            // 保存旧值
            shm_arr[i].old_val = shm_arr[i].new_val;

            // 根据数据类型更新新值
            switch (shm_arr[i].type)
            {
            case DATA_TYPE_BOOL: // BOOL (type=1)
                shm_arr[i].new_val.b_val = (strcmp(value, "1") == 0) ? 1 : 0;
                break;

            case DATA_TYPE_INT: // INT (type=2)
                shm_arr[i].new_val.i_val = atoi(value);
                break;

            case DATA_TYPE_FLOAT: // FLOAT (type=3)
                shm_arr[i].new_val.f_val = atof(value);
                break;
            }

            shm_arr[i].ret = 0; // 成功
            printf("更新共享内存: key=%d, value=%s (位置:%d)\n", key, value, i);
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
            break;
    }
<<<<<<< HEAD
    
    device->ret = 0; // 成功
    
    printf("更新共享内存: key=%d, 值=", key);
    switch (device->type) {
        case DATA_TYPE_BOOL: printf("%d", device->new_val.b_val); break;
        case DATA_TYPE_INT: printf("%d", device->new_val.i_val); break;
        case DATA_TYPE_FLOAT: printf("%.2f", device->new_val.f_val); break;
    }
    printf("\n");
    
    pthread_mutex_unlock(&shm_mutex);
}

// JSON数据处理（兼容旧版cJSON）
void process_json_data(char *json_str) {
=======

    pthread_mutex_unlock(&shm_mutex);
}

// 修改后的JSON数据处理函数
void process_json_data(char *json_str)
{
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
    cJSON *root = cJSON_Parse(json_str);
    if (!root)
    {
        printf("JSON解析失败: %s\n", json_str);
        return;
    }
<<<<<<< HEAD
    
    // 解析数据节点
=======

    // 解析设备数据
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
    cJSON *data_obj = cJSON_GetObjectItem(root, "data");
    if (!data_obj)
    {
        printf("未找到data节点\n");
        cJSON_Delete(root);
        return;
    }

    // 遍历所有STM32设备
<<<<<<< HEAD
    for (int i = 0; i < stm32_device_count; i++) {
        cJSON *value_obj = cJSON_GetObjectItem(data_obj, stm32_devices[i].name);
        if (!value_obj) {
            // 尝试使用key作为备选
            char key_str[16];
            snprintf(key_str, sizeof(key_str), "%d", stm32_devices[i].key);
            value_obj = cJSON_GetObjectItem(data_obj, key_str);
        }
        
        if (!value_obj) {
            printf("未找到设备 %s (key=%d) 的数据\n", 
                  stm32_devices[i].name, stm32_devices[i].key);
            continue;
        }
        
        char value_str[32] = {0};
        
        // 使用直接类型判断（兼容旧版cJSON）
        if (value_obj->type == cJSON_Number) {
            if (stm32_devices[i].type == DATA_TYPE_FLOAT) {
                snprintf(value_str, sizeof(value_str), "%.4f", value_obj->valuedouble);
            } else {
                snprintf(value_str, sizeof(value_str), "%d", value_obj->valueint);
            }
        } 
        else if (value_obj->type == cJSON_String) {
            strncpy(value_str, value_obj->valuestring, sizeof(value_str)-1);
        }
        else if (value_obj->type == cJSON_True) {
            snprintf(value_str, sizeof(value_str), "%d", 1);
        }
        else if (value_obj->type == cJSON_False) {
            snprintf(value_str, sizeof(value_str), "%d", 0);
=======
    for (int i = 0; i < stm32_device_count; i++)
    {
        if (i >= STM32_DEVICE_COUNT)
            break;

        // 使用设备名作为键查找值
        cJSON *value_obj = cJSON_GetObjectItem(data_obj, stm32_devices[i].name);
        if (!value_obj)
        {
            // 尝试使用key作为备选查找方式
            char key_str[16];
            snprintf(key_str, sizeof(key_str), "%d", stm32_devices[i].key);
            value_obj = cJSON_GetObjectItem(data_obj, key_str);

            if (!value_obj)
            {
                printf("未找到设备 %s (key=%d) 的数据\n",
                       stm32_devices[i].name, stm32_devices[i].key);
                continue;
            }
        }

        char value_str[20] = {0};

        // 根据数据类型获取值 (不使用cJSON_Is*辅助函数)
        if (value_obj->type == cJSON_Number)
        {
            // 根据设备类型处理值
            if (stm32_devices[i].type == DATA_TYPE_FLOAT)
            { // FLOAT (type=3)
                snprintf(value_str, sizeof(value_str), "%.2f", value_obj->valuedouble);
            }
            else
            { // BOOL or INT
                snprintf(value_str, sizeof(value_str), "%d", (int)value_obj->valuedouble);
            }
        }
        else if (value_obj->type == cJSON_String)
        {
            strncpy(value_str, value_obj->valuestring, sizeof(value_str) - 1);
        }
        else if (value_obj->type == cJSON_True)
        {
            strcpy(value_str, "1");
        }
        else if (value_obj->type == cJSON_False)
        {
            strcpy(value_str, "0");
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
        }
        else
        {
            printf("设备 %s 的值类型无效 (类型:%d)\n", stm32_devices[i].name, value_obj->type);
            continue;
        }

        // 更新共享内存
        update_shared_memory(stm32_devices[i].key, value_str);
    }

    cJSON_Delete(root);
}

int main(int argc, char const *argv[])
{
    if (argc < 2)
    {
        printf("Usage: %s <port>\n", argv[0]);
        return -1;
    }

    // 1. 解析配置文件
    if (parse_config("./node.json") < 0)
    {
        return -1;
    }

    // 2. 初始化共享内存
    if (init_shared_memory() != 0)
    {
        printf("共享内存初始化失败\n");
        return -1;
    }

    // 3. 创建TCP套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket err");
        return -1;
    }

    // 设置SO_REUSEADDR选项
    int reuse = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
    {
        perror("setsockopt(SO_REUSEADDR) failed");
        close(sockfd);
        return -1;
    }

    printf("socket fd: %d\n", sockfd);

    // 4. 绑定套接字
    struct sockaddr_in saddr, caddr;
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(atoi(argv[1]));
    saddr.sin_addr.s_addr = INADDR_ANY;
    socklen_t len = sizeof(caddr);

    if (bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
    {
        perror("bind err");
        close(sockfd);
        return -1;
    }
    printf("bind ok\n");

    // 5. 监听套接字 (队列长度设为1，因为只处理一个客户端)
    if (listen(sockfd, 1) < 0)
    {
        perror("listen err");
        close(sockfd);
        return -1;
    }
    printf("listen ok\n");
<<<<<<< HEAD
    
    signal(SIGCHLD, handler);
    
    // 7. 接受客户端连接
    while (1) {
        int acceptfd = accept(sockfd, (struct sockaddr *)&caddr, &len);
        if (acceptfd < 0) {
            perror("accept err");
            continue;
        }
        
        g_acceptfd = acceptfd; // 更新全局连接描述符
        printf("accept fd: %d\n", acceptfd);
        printf("client port: %d, ip: %s\n", 
               ntohs(caddr.sin_port), inet_ntoa(caddr.sin_addr));
        
        pid_t pid = fork();
        if (pid < 0) {
            perror("fork err");
            close(acceptfd);
            continue;
        } else if (pid == 0) {
            // 子进程处理客户端连接
            close(sockfd);
            
            char buf[1024] = {0};
            while (1) {
                int ret = recv(acceptfd, buf, sizeof(buf) - 1, 0);
                if (ret < 0) {
                    perror("recv err");
                    break;
                } else if (ret == 0) {
                    printf("client disconnected\n");
                    break;
                } else {
                    buf[ret] = '\0';
                    printf("Received JSON: %s\n", buf);
                    process_json_data(buf);
                    memset(buf, 0, sizeof(buf));
                }
            }
            
            close(acceptfd);
            exit(0);
        } else {
            // 父进程继续监听新连接
            close(acceptfd);
=======

    // 6. 接受单个客户端连接 (移除了while循环)
    int acceptfd = accept(sockfd, (struct sockaddr *)&caddr, &len);
    if (acceptfd < 0)
    {
        perror("accept err");
        close(sockfd);
        return -1;
    }

    // 7. 创建控制线程处理消息队列
    pthread_t tid;
    int *pfd = malloc(sizeof(int));
    *pfd = acceptfd;
    if (pthread_create(&tid, NULL, handler_thread, pfd) != 0)
    {
        perror("创建控制线程失败");
        close(acceptfd);
        close(sockfd);
        return -1;
    }
    pthread_detach(tid); // 分离线程，自动回收资源

    printf("accept fd: %d\n", acceptfd);
    printf("client port: %d, ip: %s\n", ntohs(caddr.sin_port), inet_ntoa(caddr.sin_addr));

    // 8. 接收客户端数据 (主线程处理)
    char buf[1024] = {0};
    while (1)
    {
        int ret = recv(acceptfd, buf, sizeof(buf) - 1, 0);

        if (ret < 0)
        {
            perror("recv err");
            break;
        }
        else if (ret == 0)
        {
            printf("client disconnected\n");
            break;
        }
        else
        {
            buf[ret] = '\0';
            printf("Received JSON: %s\n", buf);

            // 处理JSON数据
            process_json_data(buf);

            // 清空缓冲区
            memset(buf, 0, sizeof(buf));
>>>>>>> 1129cb3873237fc7cb485274830f2512582554a1
        }
    }

    // 9. 客户端断开后，清理资源
    close(acceptfd); // 关闭客户端连接
    close(sockfd);   // 关闭监听套接字
    if (stm32_devices)
        free(stm32_devices);
    return 0;
}